import javax.swing.tree.TreeNode;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

//层序遍历

public class BinaryTree {
    //基础void版(队列实现)
    public void levelOrder1(TreeNode root) {
        if (root==null) return;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while(!queue.isEmpty()) {
            TreeNode cur = queue.poll();//循环方式：要让root不断更新,所以引入了cur
            System.out.println(cur.val);
            if (root.left != null) {
                queue.offer(root.left);
            }
            if (root.right != null) {
                queue.offer(root.right);
            }
        }
    }

    //返回值为二维数组
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> List = new ArrayList<>();
        //空树
        if(root == null) return List;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int size = queue.size();
            while(size-->0) {
                TreeNode cur = queue.poll();
                list.add(cur.val);
                if(cur.left != null) {
                    queue.offer(cur.left);
                }
                if(cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            List.add(list);
        }
        Collections.reverse(List);
        return List;
    }
}
